package com.xujie.application.weather.temperatureAnalysis;

import cn.hutool.core.date.DateUtil;
import com.xujie.common.exceptions.weather.AnalyzeTemperatureException;
import com.xujie.common.utils.DateUtils;
import com.xujie.infra.entity.WeatherDaily;
import com.xujie.infra.entity.WeatherRecords;
import com.xujie.infra.mapper.WeatherDailyMapper;
import com.xujie.infra.service.WeatherService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计分析近七日温度数据
 * @author Xujie
 * @since 2024/12/21 10:42
 **/
@Slf4j
@Component
public class TemperatureAnalyzer {
	@Resource
	private WeatherService weatherService;
	@Resource private WeatherDailyMapper weatherDailyMapper;

	@Scheduled(cron = "${weather.temperature.interval}", zone = "Asia/Shanghai")
	public void analyzeTemperature() {
		try {
			log.info("开始分析近七日温度数据");
			// 获取数据
			List<WeatherRecords> weekWeatherRecords = weatherService.getWeekWeatherRecords(new DateTime());
			// 分析数据
			Map<Date, WeatherDaily> weatherDailyMap = new HashMap<>();
			// 1、按天统计最高温度、最低温度、平均温度。
			for (WeatherRecords weatherRecords : weekWeatherRecords) {
				// 获取当天的起始时间
				Date dataDate = DateUtils.getStartOfDay(weatherRecords.getDataDate());

				// 从 Map 中获取当天的 WeatherDaily 对象
				WeatherDaily weatherDaily = weatherDailyMap.get(dataDate);

				if (weatherDaily == null) {
					// 如果当天的 WeatherDaily 不存在，初始化一个新的对象
					weatherDaily = new WeatherDaily();
					weatherDaily.setDataDate(dataDate);
					weatherDaily.setHighest(weatherRecords.getTemperature());
					weatherDaily.setLowest(weatherRecords.getTemperature());
					weatherDaily.setSumTemperature(weatherRecords.getTemperature()); // 初始化累积温度
					weatherDaily.setRecordCount(1); // 初始化记录计数
					weatherDaily.setCity(weatherRecords.getCity());
					weatherDaily.setAverage(weatherRecords.getTemperature()); // 设置初始平均值
					weatherDailyMap.put(dataDate, weatherDaily); // 放入 Map 中
				} else {
					// 更新最高温度
					weatherDaily.setHighest(Math.max(weatherDaily.getHighest(), weatherRecords.getTemperature()));
					// 更新最低温度
					weatherDaily.setLowest(Math.min(weatherDaily.getLowest(), weatherRecords.getTemperature()));
					// 累加温度总和
					weatherDaily.setSumTemperature(weatherDaily.getSumTemperature() + weatherRecords.getTemperature());
					// 增加记录计数
					weatherDaily.setRecordCount(weatherDaily.getRecordCount() + 1);
					// 重新计算平均值
					weatherDaily.setAverage(weatherDaily.getSumTemperature() / weatherDaily.getRecordCount());
				}
			}

			// 获取列表
			List<WeatherDaily> weatherDailies = weatherDailyMap.values().stream().toList();
			// 2、保存数据
			weatherDailyMapper.batchInsert(weatherDailies);


			log.info("分析近七日温度数据完成");
		} catch (Exception e) {

			throw AnalyzeTemperatureException.INSTANCE;
		}
	}
}
